//
//  FormRelationshipsViewController.m
//  cliqset
//
//  Created by David Hinson on 4/2/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "FormRelationshipsViewController.h"
#import "cliqsetAppDelegate.h"
#import "Relationship.h"

@implementation FormRelationshipsViewController

@synthesize pendingRelationships;
@synthesize hoverView;
@synthesize mode;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Pending Requests";
	
    hoverView.center   = [self view].center;
	
	[[self view] addSubview:hoverView];
    [[self view] bringSubviewToFront:hoverView];
}

#pragma mark ---- table handling ----

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (void)showHoverView:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		hoverView.alpha = 0.85;
	}
	else
	{
		hoverView.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	return [myApp.pendingRelationships count];
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 63.0;
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
    
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
	
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];	
	cell.contentView.backgroundColor = [UIColor whiteColor];
	
	UIColor* textColor = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	// Dereference our contact	
	Target * request = (Target *)[myApp.pendingRelationships objectAtIndex:indexPath.row];
	
	NSData* imageData         = request.avatarBlob;
	UIImage * graphic         = (UIImage*)[[UIImage alloc] initWithData:imageData];
	
	UIImageView *showImage    = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, ((54-(40 * graphic.size.height / graphic.size.width))/2.0), 40.0, 40.0 * (graphic.size.height / graphic.size.width))];
    showImage.opaque          = NO;    
	showImage.image           = graphic;
	
	UIView * imageBackground  = [[UIView alloc] init];
	CGRect adjFrame           = showImage.frame;
	adjFrame.origin.x--;
	adjFrame.origin.y--;
	adjFrame.size.height+=2;
	adjFrame.size.width+=2;
	imageBackground.backgroundColor = [UIColor grayColor];
	imageBackground.frame     = adjFrame;
	[cell addSubview:imageBackground];
	[imageBackground release];
	
	// Fonts for Labels
	UIFont* teeny_font      = [UIFont systemFontOfSize:14];
	UIFont* bold_large_font = [UIFont boldSystemFontOfSize:18];
	
	// Allocate labels
	UILabel *nameLabel        = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 7.0, 200.0, 20.0)];
	UILabel *jobLabel         = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 27.0, 200.0, 20.0)];
	
	// Build Name Label
	nameLabel.text			  = [@"" stringByAppendingFormat:@"%@ %@", request.givenName, request.familyName];
	nameLabel.font            = bold_large_font;
	
	nameLabel.backgroundColor        = [UIColor clearColor];
	jobLabel.backgroundColor         = [UIColor clearColor];
	
	// Set text color
	nameLabel.textColor       = textColor;
	jobLabel.textColor        = textColor;
	cell.textColor            = textColor;
	
	// Set label in cell
	[cell addSubview:nameLabel];
	
	// Do we have a hometown?
	if (request.hometown) {
		// Build company label
		jobLabel.text		  = request.hometown;
		jobLabel.font         = teeny_font;
		
		// Set label in cell
		[cell addSubview:jobLabel];
	}
	
	// Add image to cell
	[cell addSubview:showImage];
	
	UIImage * accept = [UIImage imageNamed:@"accept.png"];
	UIImage * delete = [UIImage imageNamed:@"delete.png"];
	
	UIButton * acceptButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
	UIButton * deleteButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
	acceptButton.frame = CGRectMake(240, 10, 70, 20);
	deleteButton.frame = CGRectMake(240, 35, 70, 20);
	
	acceptButton.tag = indexPath.row;
	deleteButton.tag = indexPath.row;
	
	acceptButton.font = [UIFont systemFontOfSize:10];
	deleteButton.font = [UIFont systemFontOfSize:10];
	
	[acceptButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	[deleteButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	
	[acceptButton setTitle:@"  Accept" forState:UIControlStateNormal];
	[deleteButton setTitle:@"  Ignore" forState:UIControlStateNormal];

	[acceptButton addTarget:self action:@selector(acceptRelationship:) forControlEvents:UIControlEventTouchUpInside];
	[deleteButton addTarget:self action:@selector(ignoreRelationship:) forControlEvents:UIControlEventTouchUpInside];
	
	UIImageView * aView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 2, 16, 16)];
	UIImageView * dView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 2, 16, 16)];
	
	aView.image = accept;
	dView.image = delete;
	
	[acceptButton addSubview:aView];
	[aView release];
	[deleteButton addSubview:dView];
	[dView release];
	
	[cell addSubview:acceptButton];
	[cell addSubview:deleteButton];
	
	// Cleanup our junk
	[acceptButton release];
	[deleteButton release];
	[showImage release];
	[graphic release];
	[nameLabel release];
	[jobLabel release];
	
	return cell;
}

// Accept relationship
-(void)acceptRelationship:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	UIButton * btn = (UIButton*)id;
	NSLog(@"accept Relationship %d", btn.tag);
	Target * request = (Target*)[myApp.pendingRelationships objectAtIndex:btn.tag];
	[myApp.cliqset requestRelationship:request.userIdentifier];
	[myApp.pendingRelationships removeObjectAtIndex:btn.tag];
	[self.pendingRelationships reloadData];
	[myApp reloadProfileTable];
	
	for (int x=0; x<[myApp.notifications count]; x++) {
		UIView * view = (UIView *)[myApp.notifications objectAtIndex:x];
		if (view.tag == -2) {
			[myApp.notifications removeObjectAtIndex:x];
			NSString * countString = [NSString stringWithFormat:@"%d", [myApp.pendingRelationships count]];
			if ([myApp.pendingRelationships count]>0) {[myApp resetPendingRelationships]; [myApp showRelationshipsBadge:countString];} else {[myApp showRelationshipsBadge:nil];}
		}
	}
	
	[myApp reloadProfileTable];
	// Update our relationships tab so that we are up to snuff with new additions
	[myApp.cliqset getRelationships];
	[myApp reloadRelationshipsTable];
}

// Ignore relationship
-(void)ignoreRelationship:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	UIButton * btn = (UIButton*)id;
	NSLog(@"ignore Relationship %d", btn.tag);
	Target * request = (Target*)[myApp.pendingRelationships objectAtIndex:btn.tag];
	[myApp.cliqset deleteRelationship:request.userIdentifier];
	[myApp.pendingRelationships removeObjectAtIndex:btn.tag];
	[self.pendingRelationships reloadData];
	
	for (int x=0; x<[myApp.notifications count]; x++) {
		UIView * view = (UIView *)[myApp.notifications objectAtIndex:x];
		if (view.tag == -2) {
			[myApp.notifications removeObjectAtIndex:x];
			NSString * countString = [NSString stringWithFormat:@"%d", [myApp.pendingRelationships count]];
			if ([myApp.pendingRelationships count]>0) {[myApp resetPendingRelationships]; [myApp showRelationshipsBadge:countString];} else {[myApp showRelationshipsBadge:nil];}
			}
		}
	
	[myApp reloadProfileTable];
}

-(void)reloadData {
	[self.pendingRelationships reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
}

- (void)dealloc {
	[hoverView release];
	[pendingRelationships release];
    [super dealloc];
}

@end
